requireJS(['constant', 'site', 'handlebars', 'public', 'static/js/page/common/common.js'], function (Constant, site, Handlebars, Public, Common) {
    Constant.initHandlebars(Handlebars)
    Public.initProductSearch();
    //Public.initApplyTerm();

    //全选功能
    $("input[name='ch_id_all']").on('click', function () {
        var _checked = $("input[name='ch_id']")
        if ($(this).prop('checked')) {
            _checked.prop('checked', true)
        }
        else {
            _checked.prop('checked', false)
        }
    })

    $(document).on('click', '.icon-wrong', function () {
        $(this).parents('.winBox').hide();
    })

    var editor;
    var willBeSaved;
    var order_id;
    var task_id;
    var node_id;
    var repayment_way;
    var loan_way;
    var paymentObject;
    var loan_way_object;
    var editors = {};
    var arr = [];

    //是否已生成还款计划字段
    var isGenerated = false;

    var url = {
        queryOrder: 'manager/selectOrderPageList.do',
        queryAdminRoleByRole: "manager/queryAdminRoleByRoleId.do",
        selectPageLogList: "manager/selectPageLogList.do",
        selectOrderSourceList: "manager/selectOrderSourceList.do",
        queryAdminRoleByRoleId: "manager/queryAdminRoleByRoleId.do",
        selectLoanMethodList: "manager/selectLoanMethodList.do",
        contractSigned: "manager/contractSigned.do",
        submitMortgage: "manager/submitMortgage.do",
        backProcess: "manager/backProcess.do",
        contractBatchDownload: "manager/contractBatchDownload.do",
        getActivitiProccessImage: "manager/getActivitiProccessImage.do",
        ajaxqueryRegion: "manager/ajaxqueryRegion.do",
        contractSignedNow: "manager/contractSignedNow.do",
        selectFirstList: "manager/selectFirstList.do"
    }

    //渲染搜索框的贷款方式
    site.send({
        url: url.selectLoanMethodList,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == '1') {
                var source = $("#loanMethod_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data
                var html = template(list)
                loan_way_object = list.content;
                $('#loan_way_select').append(html);
            }
        }
    })

    //查询阐述
    var frontData = {
        roleId: Constant.getAurlparam("roleId"),
        audit_status: 0,
        susp_status: 1,
        pageNum: 1
    }
    var allDownLoadData = {};
    var replacePayData = {};
    var updataPersonalData = {};
    // 初始化
    var all_select = function (frontData) {
        //头部日期
        site.send({
            url: "manager/selectApplyTermList.do",
            // async: false,
            data: {},
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    var list = JSON.parse(data)
                    var template2 = Handlebars.compile($("#contract_head_date_tpl").html())
                    var html2 = template2(list)
                    $("#contract_head_date").html(html2)
                } else {
                    Constant.fn.Message('F', list.msg);
                }


            }
        })
        //请求服务端查询待签订合同的订单
        site.send({
            // async: false,
            url: url.queryOrder,
            data: frontData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == '1') {
                    if (list.content) {
                        $("#total").text(list.content.total);
                        $('.contract-page-container').createPager({
                            current: frontData.pageNum,
                            total: list.content.total,
                            pageSize: list.content.pageSize,
                            needInput: false,
                            backFn: function (current) {
                                frontData.pageNum = current;
                                all_select(frontData);
                            }
                        })
                    }
                    var source = $("#contract_management_tpl").html();
                    var template = Handlebars.compile(source);

                    var menuIndex = getAurlparam('h') || 0;
                    var thirdMenusIndex = getAurlparam('t') || 0;
                    var leftIndex = getAurlparam('i') || 0;

                    var storageContent = JSON.parse(localStorage.getItem('content'));

                    var obj = {
                        content: list,
                        fourthMenus: storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children || {}
                    }

                    var html = template(obj);
                    $("#contract_management").html(html);
                    // 分页

                    Public.record('t_order_public')

                } else {
                    Constant.fn.Message('F', list.msg)
                }


                onBindFun();
            }
        });


    }


    all_select(frontData);
    var rapayPlan_data = {};//还款计划传入数据
    var new_numData = {};//生成订单号
    var commitDocData = {};//保存模板
    var previewData = {};//预览模板
    var newData = {}; //生成合同编号的参数
    var contractContent;
    var contract_num;//合同编号
    var submitMortgageData = {}//上传登记

    //流转查询出角色
    function queryRole(order_id, a) {
        site.send({
            url: url.queryAdminRoleByRole,
            data: {
                order_id: order_id
            },
            callback: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    var source = $("#role_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data.content
                    var html = template(list)
                    $(a).parents('.winBox').find('.role_list').append(html)
                }
                /*else {
                    $('.winBox').toggle();
                }*/
            }
        })
    }

    //节点表单审核单选按钮
    $('input[name="faceResult"][value="1"]').on('change', function () {
        queryRole(order_id, this);
    })

    $('input[name="faceResult"][value="2"]').on('change', function () {
        $('.role').remove();
    })

    function onBindFun() {



        // 选择操作select
        $(".operation_list").on('change', function () {
            task_id = $(this).data('taskid');
            order_id = $(this).data('id');
            node_id = $(this).data('nodeid');
            paymentObject = $(this).data('paymentobject');
            repayment_way = $(this).data('repayment_way');
            loan_way = $(this).data('loan_way')
            var obj = $(this).find("option:selected");
            if (obj.val() == 'checkOrder') {
                pjaxGo('loanIng/contractManager/detail.html?order_id=' + $(this).data('id') + "&product_id=" + $(this).data('productid') + "&task_id=" + $(this).data('taskid'));
            }
            // 合同编号
            if (obj.val() == 'contractNumber') {
                rapayPlan_data.oid = $(this).data('id');//订单Id
                new_numData.oid = $(this).data('id');
                newData.oid = $(this).data('id');
                commitDocData.oid = $(this).data('id');
                $.each(loan_way_object, function (i, e) {
                    if (loan_way == e.id) {
                        $('.loan_way').html(e.name);
                    }
                })
                $("#repayPlan_content").show();
                $("#main_content").hide();
                $("#toOrder_content").hide();
                contract_num = 'doc1Show'
                //repayPlan_fun();
                selecDocList();
                selectFundPlan();
                $(".operation_list").val('-1')
            }
            //批量下载
            if (obj.val() == 'severalDownload') {
                allDownLoadData.oid = $(this).data('id');
                allDownLoad();
                $(".operation_list").val('-1')
            }
            if (obj.val() == 'repayPlan') {
                rapayPlan_data.oid = $(this).data('id');//订单Id
                new_numData.oid = $(this).data('id');
                newData.oid = $(this).data('id');
                commitDocData.oid = $(this).data('id');
                $.each(loan_way_object, function (i, e) {
                    if (loan_way == e.id) {
                        $('.loan_way').html(e.name);
                    }
                })
                $("#repayPlan_content").show();
                $("#main_content").hide();
                $("#toOrder_content").hide();
                //repayPlan_fun();
                selecDocList();
                selectFundPlan();
                $(".operation_list").val('-1')

            }
            // // 上传登记
            if (obj.val() == 'uploadSign') {
                $(".UploadaRegister_Winbox").show();
                submitMortgageData.oid = $(this).data('id');
                order_id = $(this).data('id')
                task_id = $(this).data('taskid')
                $(".operation_list").val('-1')
            }
            //付款对象
            if (obj.val() == 'payObject') {
                $(".pay_object_winBox").toggle();
                replacePayData.oid = $(this).data('id');//订单Id
                $(".operation_list").val('-1')

                var template = Handlebars.compile($("#paymentObject_tpl").html());
                $("#paymentObject").html(template(paymentObject));

                $("#payObjectBtn").unbind().on('click', function () {
                    replacePayData.remarks = $("#payObjectTarea").val();
                    replacePayData.payment_object = $("input[name='briskResult']:checked").val();
                    site.send({
                        //async: false,
                        url: 'manager/replacePaymentObject.do',
                        data: replacePayData,
                        callback: function (data) {
                            var list = JSON.parse(data);
                            if (list.type == '1') {
                                Constant.fn.Message('T', list.msg);
                                $(".pay_object_winBox").hide();
                                pjaxReload()
                            } else {
                                Constant.fn.Message('F', list.msg);
                            }
                        }
                    })

                })

            }
            //修改收款
            if (obj.val() == 'changeGathering') {
                updataPersonalData.pid = $(this).data('pid');
                updataPersonalData.oid = $(this).data('oid');

                $(".modify_money_winBox").toggle();
                site.send({
                    //async: false,
                    url: 'manager/selectPersonalInfo.do',
                    data: {
                        pid: $(this).data('pid')
                    },
                    callback: function (data) {
                        var list = JSON.parse(data);
                        if (list.type == '1') {
                            $("#payee").val(list.content.payee);
                            $("#account").val(list.content.account);
                            $("#bank").val(list.content.bank);
                        } else {
                            Constant.fn.Message('F', list.msg);
                        }
                    }
                })
                $(".operation_list").val('-1')
            }
            if (obj.val() == 'backReview') {
                arr = [{
                    taskId: task_id,
                    orderId: order_id,
                    nodeId: node_id
                }]
                $(".back_order_winBox").toggle();
                $(".operation_list").val('-1')
            }
            if (obj.val() == 'contractWait') {
                $(".determineWinbox").show();
                $(".undeterminedRemark").val("");
                determineFun($(this).data('id'), $(this).data('taskid'));
                $(".operation_list").val('-1')
            }
            if (obj.val() == 'signeContract') {
                order_id = $(this).data('id');
                task_id = $(this).data('taskid')
                /*if(loan_way == '2'){
                    $("#loanSpecial").hide();
                }
                else{
                    $("#loanSpecial").show();
                }*/

                //初始化弹框里的内容
                $('.contractRemark').val("");
                $('#orderSource_content').val("");
                $('input[name="shareOrderid"]').prop('checked', false);
                $('.shareOrder').hide();
                $('input[name="faceResult"]').prop('checked', false);
                $('.role').remove();
                $('[id^="gallery"]').html('');
                site.send({
                    url: url.contractSignedNow,
                    data: {
                        id: order_id
                    },
                    callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == 1) {
                            if (data.content) {
                                $("#orderSource_content option[data-id=" + data.content.os_id + "]").prop('selected', true);

                                if (data.content.map_share) {
                                    if (data.content.map_share[0]) {
                                        $("input[name='shareOrderid'][value='1']").prop('checked', true);
                                        $.each(data.content.map_share, function (i, e) {
                                            if (i === 0) {
                                                $('.shareOrder').show();
                                                $('.sharePeople').val(e.name);
                                                $('.shareRatio').val(e.ratio);
                                            } else {
                                                $('.shareOrder').after('<tr class="shareOrder public-content-tab ng-scope">\n' +
                                                    '                                    <td>&nbsp;</td>\n' +
                                                    '                                    <td style="text-align: left;padding-left: 0;padding-top:5px;padding-bottom: 15px;">\n' +
                                                    '                                       <div ng-repeat="(key,items) in _shareOrder track by $index" style="padding-bottom:5px;" class="ng-scope">\n' +
                                                    '                                        <span class="pad"><input type="text" style="width:150px;" value="' + e.name + '" placeholder="输入姓名" ng-model="items.shareName" class="sharePeople"></span>\n' +
                                                    '                                        <span class="pad" style="margin-left:5px;"><input onlyinputnum="2" placeholder="输入比例" type="text" style="width:80px" value="' + e.ratio + '" ng-model="items.shareRatio" class="shareRatio"> %</span>\n' +
                                                    '                                        <span class="del delShare ng-scope">删除</span>\n' +
                                                    '                                    </div>\n' +
                                                    '                                    </td>\n' +
                                                    '                                </tr>');

                                                $('.delShare').unbind().on('click', function () {
                                                    $(this).parents('tr').remove();
                                                })
                                            }
                                        })
                                    }
                                }

                                $.each(data.content.attList, function (i, e) {
                                    $.each(e.attach_img, function (ii, ee) {
                                        $('[attachid=' + e.attach_name + ']').append('<li href="' + ee + '">   \n' +
                                            '<img class="img_00" src="' + ee + '/tupian_compress" url="' + ee + '">\n' +
                                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                                            '</i>\n' +
                                            '</li>');
                                    })
                                })

                                $('[id^="gallery"]').parents('.winBox1').viewer('destroy').viewer();
                                Constant.fn.initScroll();

                                //删除单张图片
                                $('.delSingleAttach').unbind().on('click', function (e) {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    $(this).parents('li').remove();
                                    Constant.fn.initScroll();
                                })
                            }
                            /*var source = $("#contractSigned_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content
                            var html = template(list)
                            $("#contractSigned_list").html(html);*/
                        }
                    }
                })


                $('.contract_winBox').toggle();

                site.send({
                    url: url.selectOrderSourceList,
                    callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == 1) {
                            var template = Handlebars.compile($("#orderSource_content_tpl").html());
                            $("#orderSource_content").html(template(data.content));
                        }
                        else {

                        }
                    }
                })

                /*site.send({
                    url: url.queryAdminRoleByRoleId,
                    data: {
                        order_id: obj.data('id')
                    },
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            var source = $("#role_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content
                            var html = template(list)
                            $('#role_list').append(html)
                        }
                        /!*else {
                            $('.winBox').toggle();
                        }*!/
                    }
                })*/
                $(".operation_list").val('-1')
            }
            if ($(this).val() == 'lookProcess') {
                $('.processBox').remove()
                site.send({
                    url: url.getActivitiProccessImage,
                    data: {
                        taskId: task_id,
                    },
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            var source = $("#process_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data.content
                            var html = template(list)
                            $('.lookProcess').append(html)
                            $('.lookProcess_winBox').toggle();
                        } else {
                            Constant.fn.Message("F", data.msg);
                        }
                    }
                })
                $(".operation_list").val('-1')
                //queryDelegate(1);
            }
            if ($(this).val() == 'submitVisit') {
                Common.visit(order_id);
                Common.init(3,order_id);
            }
        })

        $('.sureSign').on('click', function () {
            var data = {
                oid: order_id,
                adminId: $(".contract_winBox .role_list option:selected").val(),
                orderSourceId: $('#orderSource_content option:selected').data('id'),
                remarks: $('.contractRemark').val(),
                taskId: task_id,
                type: $('.contract_winBox input[name="faceResult"]:checked').val()
            }
            var attachImgLists = new Array();
            $.each($('.contract_winBox [attachid]'), function (i, e) {
                if ($(e).find('li').length) {
                    var attachImg = new Array();
                    $.each($(e).find('li'), function (ii, ee) {
                        attachImg.push($(ee).attr('href'));
                    })
                    attachImgLists.push({
                        attachName: $(e).attr('attachid'),
                        attachImg: attachImg
                    })
                }
            })
            if (attachImgLists.length) {
                data.attachImgLists = JSON.stringify(attachImgLists)
            }
            if ($('input[name="shareOrderid"]:checked').val() == 1) {
                var shareOrder = new Array();
                $.each($('.shareOrder'), function (i, e) {
                    shareOrder.push({
                        shareName: $(e).find('.sharePeople').val(),
                        shareRatio: $(e).find('.shareRatio').val()
                    })
                })
                data.shareOrder = JSON.stringify(shareOrder);
            }
            if (!data.orderSourceId) {
                Constant.fn.Message('I', '请选择订单渠道');
                return;
            }
            if (shareOrder) {
                for (var i = 0; i < shareOrder.length; i++) {
                    if (!shareOrder[i].shareName || !shareOrder[i].shareRatio) {
                        Constant.fn.Message('I', '请填写完整的参股信息');
                        return;
                    }
                }
            }
            if (!data.type) {
                Constant.fn.Message('I', '请选择审核结果');
                return;
            }
            if (data.type == '1' && !data.adminId) {
                Constant.fn.Message('I', '请选择提交对象');
                return;
            }
            if (!data.remarks) {
                Constant.fn.Message('I', '请输入备注');
                return;
            }
            site.send({
                url: url.contractSigned,
                data: data,
                callback: function (data) {
                    data = JSON.parse(data);
                    if (data.type == 1) {
                        $('.contract_winBox').toggle();
                        Constant.fn.Message('T', data.msg);
                        pjaxReload()
                    }
                    else {
                        Constant.fn.Message('F', data.msg);
                    }
                }
            })
        })

        $('.delSign').on('click', function () {
            $('.contract_winBox').toggle();
        })
        //下拉框选中获取值
        $("#role_select").on('change', function () {
            userId = $(this).find("option:selected").val();
        })

        $("input[name='shareOrderid'][value='0']").on('click', function () {
            $('.shareOrder').hide();
        })

        $("input[name='shareOrderid'][value='1']").on('click', function () {
            $('.shareOrder').show();
        })

        $(".addShare").on('click', function () {
            $('.shareOrder:last').after('<tr class="shareOrder public-content-tab ng-scope">\n' +
                '                                    <td>&nbsp;</td>\n' +
                '                                    <td style="text-align: left;padding-left: 0;padding-top:5px;padding-bottom: 15px;">\n' +
                '                                       <div ng-repeat="(key,items) in _shareOrder track by $index" style="padding-bottom:5px;" class="ng-scope">\n' +
                '                                        <span class="pad"><input type="text" style="width:150px;" placeholder="输入姓名" ng-model="items.shareName" class="sharePeople"></span>\n' +
                '                                        <span class="pad" style="margin-left:5px;"><input onlyinputnum="2" placeholder="输入比例" type="text" style="width:80px" ng-model="items.shareRatio" class="shareRatio"> %</span>\n' +
                '                                        <span class="del delShare ng-scope">删除</span>\n' +
                '                                    </div>\n' +
                '                                    </td>\n' +
                '                                </tr>')

            $('.delShare').unbind().on('click', function () {
                $(this).parents('tr').remove();
            })
        })


        // 合同待定确定
        function determineFun(oid, taskId) {
            $("#determineBtn").unbind().click(function () {
                site.send({
                    async: false,
                    url: 'manager/updateOrderStatus.do',
                    data: {
                        oid: oid,
                        taskId: taskId,
                        remark: $(".undeterminedRemark").val()
                    },
                    callback: function (data) {
                        if (data.msg == '系统异常') {
                            Constant.fn.Message('F', data.msg)
                        }
                        var list = JSON.parse(data)
                        if (list.type == 1) {
                            $(".determineWinbox").toggle();
                            Constant.fn.Message('T', list.msg)
                            pjaxReload()
                        } else {
                            Constant.fn.Message('F', list.msg)
                        }
                    }
                })
            })
        }

        //批量操作下载合同

        $("#allDown_select").on('change', function () {
            var data = ''
            var selected = $(this).find("option:selected");
            $(this).find("option:first").prop("selected", false).prop("selected", true);
            $("input[name='ch_id']:checked").each(function (index, item) {
                data = data + $(item).val() + ","
            })
            data = data.substring(0, data.length - 1)
            if (selected.val() == '下载合同') {
                //删除产品
                if (!data) {
                    Constant.fn.Message('I', "未选择要下载的订单")
                    return;
                }
                //$('.delete_winBox').toggle();

                //$('.sureDel').on('click', function () {

                $('.prog-c').css('width', '0px');
                $('.prog-rate i').text('0');
                $('.package_winBox').show();
                $('.downloaded').hide();
                $('.downloading').show();

                //进度条
                var time = 0;
                var prog = 0;
                var timer = setInterval(function () {
                    time += 3;
                    prog += 11;
                    $('.prog-c').css('width', prog + 'px')
                    $('.prog-rate i').text(time);
                    if (time == 99) {
                        clearInterval(timer);
                    }
                }, 5)


                site.send({
                    url: url.contractBatchDownload,
                    data: {
                        oid: data
                    },
                    callback: function (data) {
                        data = JSON.parse(data)
                        if (data.type == 1) {
                            //$('.delete_winBox').toggle();
                            $.each(data.content.zipMap, function (i, e) {
                                window.open(e.zipUrl);
                            })

                            var source = $("#detail_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var html = template(data.content);
                            $("#detail_list").html(html);
                            Constant.fn.Message('T', data.msg);

                            //time = 100;
                            $('.prog-c').css('width', '376px');
                            $('.downloaded').show();
                            $('.downloading').hide();

                            //pjaxReload();
                        } else {
                            $('.package_winBox').hide();
                            Constant.fn.Message("F", data.msg)
                        }
                    },
                    callError: function () {

                    }
                })
                //})
            }
        })

        // 全选与全不选
        $(".all_check").click(function () {
            if (this.checked) {
                $("input[name='ch_id']").prop('checked', true);
            } else {
                $("input[name='ch_id']").prop('checked', false);
            }
//     反选
//     $("input[name='ch_id']").each(function(){
//         $(this).prop('checked',!$(this).prop('checked'))
//     });

        })

        $("input[name='ch_id']").click(function () {
            allcheck();

        })

        function allcheck() {
            var num = 0;
            var ch_id_size = $("input[name='ch_id']").size();
            $("input[name='ch_id']").each(function () {
                if ($(this).prop('checked') == true) {
                    num++;
                }
            })

            if (ch_id_size == num) {
                $(".all_check").prop('checked', true);
            } else {
                $(".all_check").prop('checked', false);

            }
        }
    }

    //退回订单确定退回
    $('.backProcess').on('click', function () {
        var remark = $('.backRemark').val();
        if (!remark) {
            Constant.fn.Message("I", '请输入备注');
            return;
        }
        site.send({
            url: url.backProcess,
            data: {
                backParameters: JSON.stringify(arr),
                remark: remark
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    $('.back_order_winBox').toggle();
                    Constant.fn.Message("T", data.msg);
                    pjaxReload();
                }
                else {
                    Constant.fn.Message('F', data.msg);
                }
            }
        })
    })

    //日期控件
    $(".datepicker").datepicker();


    // 还款计划
    //
    // document.getElementById('photo').addEventListener('change', function (e) {
    //     var files = this.files;
    //     var img = new Image();
    //     var reader = new FileReader();
    //     reader.readAsDataURL(files[0]);
    //     reader.onload = function (e) {
    //         var mb = (e.total / 1024) / 1024;
    //         // if(mb>= 2){
    //         //     alert('文件大小大于2M');
    //         //     return;
    //         // }
    //         img.src = this.result;
    //         img.style.width = "100%";
    //         img.style.height = "100%";
    //         document.getElementById('click').innerHTML = '';
    //         document.getElementById('click').appendChild(img);
    //
    //
    //     }
    //
    // });

    function repayPlan_fun() {
        rapayPlan_data.time = $(".b-date").val();//贷款发放日期
        rapayPlan_data.first_party = $(".b-name").html();//乙方姓名
        rapayPlan_data.first_party_idcard = $(".b-id-num").html();//乙方身份证号码
        var province = $("#province_list option:selected").text() ? $("#province_list option:selected").text() : '';
        var city = $("#city_list option:selected").text() ? $("#city_list option:selected").text() : '';
        var area = $("#area_list option:selected").text() ? $("#area_list option:selected").text() : '';
        //var address = province + city + area;
        var fullAddress = $("#address").html();
        rapayPlan_data.first_party_province = $("#province_list").data('id');
        rapayPlan_data.first_party_city = $("#city_list").data('id');
        rapayPlan_data.first_party_area = $("#area_list").data('id');
        rapayPlan_data.first_party_address = fullAddress;//乙方地址
        //rapayPlan_data.first_party_fullAddress = fullAddress;
        var attachimg = [];
        $.each($('[attachid=借款人签名] li'), function (i, e) {
            attachimg.push($(e).attr('href'));
        })

        rapayPlan_data.attachImg = ""; //附件图片

        if (attachimg.length) {
            rapayPlan_data.attachImg = JSON.stringify(attachimg); //附件图片
        }
        //rapayPlan_data.attachImg = JSON.stringify(attachimg); //附件图片
        if (!rapayPlan_data.first_party) {
            Constant.fn.Message("I", "请选择贷款人");
            return;
        }
        if (!rapayPlan_data.first_party_idcard) {
            Constant.fn.Message("I", "请输入身份证号");
            return;
        }
        if (!rapayPlan_data.first_party_province) {
            Constant.fn.Message("I", "请选择居住区域");
            return;
        }
        if (!rapayPlan_data.first_party_city) {
            Constant.fn.Message("I", "请选择市");
            return;
        }
        /*if (!rapayPlan_data.first_party_area) {
            Constant.fn.Message("I", "请选择区县");
            return;
        }*/
        if (!rapayPlan_data.first_party_address) {
            Constant.fn.Message("I", "请输入地址");
            return;
        }
        /*if (!rapayPlan_data.first_party_fullAddress) {
            Constant.fn.Message("I", "请输入具体地址");
            return;
        }*/
        if (!rapayPlan_data.time) {
            Constant.fn.Message("I", "请输入时间");
            return;
        }
        $(".contract_type_winBox #loanType").show();
        $(".contract_type_winBox").toggle();
    }

    function another_repayPlan_fun() {
        rapayPlan_data.time = $(".b-date").val();//贷款发放日期
        rapayPlan_data.first_party = $(".b-name").html();//乙方姓名
        rapayPlan_data.first_party_idcard = $(".b-id-num").html();//乙方身份证号码
        var province = $("#province_list option:selected").text() ? $("#province_list option:selected").text() : '';
        var city = $("#city_list option:selected").text() ? $("#city_list option:selected").text() : '';
        var area = $("#area_list option:selected").text() ? $("#area_list option:selected").text() : '';
        //var address = province + city + area;
        var fullAddress = $("#address").html();
        rapayPlan_data.first_party_province = $("#province_list").data('id');
        rapayPlan_data.first_party_city = $("#city_list").data('id');
        rapayPlan_data.first_party_area = $("#area_list").data('id');
        //rapayPlan_data.first_party_address = address;//乙方地址
        rapayPlan_data.first_party_address = fullAddress;
        var attachimg = [];
        $.each($('[attachid=借款人签名] li'), function (i, e) {
            attachimg.push($(e).attr('href'));
        })

        rapayPlan_data.attachImg = ""; //附件图片

        if (attachimg.length) {
            rapayPlan_data.attachImg = JSON.stringify(attachimg); //附件图片
        }
        if (!rapayPlan_data.first_party) {
            Constant.fn.Message("I", "请选择贷款人");
            return;
        }
        if (!rapayPlan_data.first_party_idcard) {
            Constant.fn.Message("I", "请输入身份证号");
            return;
        }
        if (!rapayPlan_data.first_party_province) {
            Constant.fn.Message("I", "请选择居住区域");
            return;
        }
        if (!rapayPlan_data.first_party_city) {
            Constant.fn.Message("I", "请选择市");
            return;
        }
        /*if (!rapayPlan_data.first_party_area) {
            Constant.fn.Message("I", "请选择区县");
            return;
        }*/
        if (!rapayPlan_data.first_party_address) {
            Constant.fn.Message("I", "请输入地址");
            return;
        }
        /*if (!rapayPlan_data.first_party_fullAddress) {
            Constant.fn.Message("I", "请输入具体地址");
            return;
        }*/
        if (!rapayPlan_data.time) {
            Constant.fn.Message("I", "请输入时间");
            return;
        }
        $(".contract_type_winBox #loanType").hide();
        $(".contract_type_winBox").toggle();
        /*site.send({
            url: 'manager/preservationGenerateFundPlan.do',//
            async: false,
            data: rapayPlan_data,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    // $("#repayPlan_content").hide();
                    // $("#main_content").show();
                    //selectFundPlan();
                    Constant.fn.Message('T', list.msg);
                    //$('.contract_type_winBox').toggle();
                    //pjaxReload();
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })*/
    }

    // 生成新的合同编号
    $(".new-contra").click(function () {
        site.send({
            url: 'manager/addContractNo.do',//
            async: false,
            data: new_numData,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == '1') {
                    $(".newNum-input").val(list.content)
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
    })
    // 保存按钮
    var commitState = 'repayPlan';
    var repaypalnState, orderId;
    $(".commit_repayPaln").click(function () {
        commit_fun(commitState);
    })
    // 预览按钮
    $(".preview_repayPaln").click(function () {
        // preview_fun(commitState);
        /*if(!isGenerated){
            Constant.fn.Message("I","请先生成还款计划");
            return;
        }*/
        preview_fun(repaypalnState, commitState)
    })
    var isDoc;//
    var lenderList = {};


    function selecDocList() {

        //渲染出借人列表
        site.send({
            url: url.selectFirstList,
            data: {
                pageNum: 1
            },
            callback: function (data) {
                data = JSON.parse(data);
                if(data.type == '1'){
                    var source = $("#lender_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data

                    if(list.content.length){
                        for (var i = 0; i < list.content.length; i++) {
                            var v = list.content[i];
                            lenderList[v.id] = v;
                        }
                    }

                    var html = template(list)
                    $('#lender_list').html(html)
                }else{
                    Constant.fn.Message("F",data.msg);
                }

                //$("#lender_list").val(perInfo.addr_city)
            }
        })

        site.send({
            url: "manager/selectDocList.do",
            async: false,
            data: new_numData,
            callback: function (data) {
                var list = JSON.parse(data)
                if (list.type == 1) {
                    isDoc = list.type;
                    willBeSaved = list.content.selectDocList;
                    if (list.content.contract_no && list.content.contract_no != '') {
                        $(".newNum-input").val(list.content.contract_no);
                        $(".newNum-input").css({'background': '#EBEBE4', 'border': '1px solid #DDDDDD'})
                        $(".new-contra").css({'background': '#EBEBE4', 'border': '1px solid #DDDDDD', 'color': '#333'})
                        $(".new-contra").unbind('click');
                    }
                    var template = Handlebars.compile($("#repayDoc_content_tpl").html());
                    $(".repayplan-PoBefore-nav").prepend(template(list));
                    var template2 = Handlebars.compile($("#repayDoc_content_tpl2").html());
                    $("#repayDoc_content2").html(template2(list));
                    UeditInit(0);
                } else {
                    Constant.fn.Message('F', list.msg)
                    isDoc = list.type;
                }
                // orderSortList
                $("#repayDoc_content2").children(".public-content").hide();
                $(".repayplan-PoBefore-nav li").each(function (i) {
                    /*if (i !== $(".repayplan-PoBefore-nav li").length - 1 && isDoc == '1') {
                        UeditInit(i);
                    }*/
                    /*if (i > 0) {
                        $(this).one('click', function () {
                            if (i !== $(".repayplan-PoBefore-nav li").length - 1 && isDoc == '1') {
                                UeditInit(i);
                            }
                        })
                    }*/
                    $(this).click(function () {
                        if (i == $(".repayplan-PoBefore-nav li").length - 1) {
                            $("#selectFundPlan_content").show();
                            $("#repayDoc_content2").children(".public-content").hide();
                            commitState = 'repayPlan';
                            repaypalnState = orderId;
                        } else {
                            $("#selectFundPlan_content").hide();
                            $("#repayDoc_content2").children(".public-content").eq(i).show();
                            $("#repayDoc_content2").children(".public-content").eq(i).siblings('.public-content').hide();
                            //editor.setContent($(".doc_content_" + i).text());
                            UeditInit(i);
                            // $(".preview_repayPaln").css({'display': 'inline-block', 'vertical-align': 'middle',})
                            //UeditInit(i);
                            commitState = i;
                            repaypalnState = i;
                        }
                        scrollFun(i);
                        $(this).children('span').children('a').addClass('activePublic');
                        $(".repayplan-PoBefore-nav li").not(this).children('span').children('a').removeClass('activePublic');

                    })
                })
                if (contract_num == 'doc1Show') {
                    if (isDoc != '-1') {
                        $("#selectFundPlan_content").hide();
                        $("#repayDoc_content2").children(".public-content").eq(0).show();
                        $("#repayDoc_content2").children(".public-content").eq(0).siblings('.public-content').hide();
                        // $(".preview_repayPaln").css({'display': 'inline-block', 'vertical-align': 'middle',})

                        //UeditInit(0);
                        commitState = 0;
                        repaypalnState = 0;

                        $(".repayplan-PoBefore-nav li").eq(0).children('span').children('a').addClass('activePublic');
                        $(".repayplan-PoBefore-nav li").eq(0).siblings(".repayplan-PoBefore-nav li").children('span').children('a').removeClass('activePublic');

                    }
                }
                // $("#repayDoc_content2").
            }
        })
    }

    $("#lender_list").on("change",function(){
        var lenderId = $(this).val();
        var v = lenderList[lenderId]
        if(lenderId){
            $("#b-name").html(v.first_party);
            $("#b-id-num").html(v.first_party_idcard);

            $("#province_list").html(v.provinceName)
            $("#province_list").attr('data-id',v.first_party_province)

            /*site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: v.first_party_province
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#city_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#city_list').html(html)
                    $("#city_list").val(v.first_party_city)
                }
            })*/
            $("#city_list").html(v.cityName)
            $("#city_list").attr('data-id',v.first_party_city)

            /*site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: v.first_party_city
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#area_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#area_list').html(html)
                    $("#area_list").val(v.first_party_area);
                }
            })*/
            $("#area_list").html(v.areaName);
            $("#area_list").attr('data-id',v.first_party_area);

            $("#address").html(v.first_party_address);
        }else{
            $("#b-name").html("");
            $("#b-id-num").html("");
            $("#province_list").html("")
            $("#city_list").html('');
            $("#area_list").html('');
            $("#address").html("");
        }
    })

    // 查询计划表
    function selectFundPlan() {

        site.send({
            url: "manager/selectFundPlan.do",
            async: false,
            data: new_numData,
            callback: function (data) {
                if (data.type == 'SYSTEM_ERROR') {
                    Constant.fn.Message('F', data.msg)
                }
                var list = JSON.parse(data)
                if (list.type == 1) {
                    // orderSortList
                    var template = Handlebars.compile($("#selectFundPlan_tpl").html());
                    $("#selectFundPlan_div").html(template(list));
                    $("#repayNumber").text(list.content.order.loanNumber);
                    var spanDocid = document.createElement("span");
                    var textNode = document.createTextNode(list.content.order.id);
                    spanDocid.style.display = 'none';
                    spanDocid.setAttribute("id", "doc_id" + list.content.order.id);
                    spanDocid.appendChild(textNode);
                    $("#selectFundPlan_content").prepend(spanDocid);
                    $("#aRealName").text(list.content.realName)//
                    $("#aidCard").text(list.content.idCard);
                    $("#b-name").html(list.content.order.first_party)
                    $("#b-id-num").html(list.content.order.first_party_idcard)
                    var list2 = list;
                    var order = list.content.order;
                    var firstPartyMap = list.content.firstPartyMap;
                    var someAttType = list.content.someAttType;
                    if (someAttType) {
                        $("#gallery").html("");
                        $.each(someAttType.attach_img, function (i, e) {
                            $("#gallery").append('<li href="' + e + '">   \n' +
                                '<img class="img_00" src="' + e + '/tupian_compress" url="' + e + '">\n' +
                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</li>')
                        })

                        //删除单张图片
                        $('.delSingleAttach').unbind().on('click', function (e) {
                            e.stopPropagation();
                            e.preventDefault();
                            $(this).parents('li').remove();
                            Constant.fn.initScroll();
                        })
                    }

                    $('[id^="gallery"]').parents('.winBox1').viewer('destroy').viewer();

                    if(order.first_party_province){
                        $("#province_list").attr('data-id',order.first_party_province)
                        $("#province_list").html(firstPartyMap.first_party_province_name);
                    }
                    /*site.send({
                        url: url.ajaxqueryRegion,
                        data: {
                            parentId: 0
                        },
                        callback: function (data) {
                            data = JSON.parse(data);
                            var source = $("#province_list_tpl").html();
                            var template = Handlebars.compile(source);
                            var list = data
                            var html = template(list)
                            $('#province_list').html(html)
                            if (order.first_party_province) {

                                $("#province_list").val(order.first_party_province)
                            }
                            //$('#rprovince_list').append(html)
                        }
                    })*/


                    if (order.first_party_province) {
                        /*site.send({
                            url: url.ajaxqueryRegion,
                            data: {
                                parentId: order.first_party_province
                            },
                            callback: function (data) {
                                data = JSON.parse(data);
                                var source = $("#city_list_tpl").html();
                                var template = Handlebars.compile(source);
                                var list = data
                                var html = template(list)
                                $('#city_list').html(html)
                                $("#city_list").val(order.first_party_city)
                            }
                        })*/
                        $("#city_list").attr('data-id',order.first_party_city)
                        $("#city_list").html(firstPartyMap.first_party_city_name);
                    }

                    if (order.first_party_city) {
                        /*site.send({
                            url: url.ajaxqueryRegion,
                            data: {
                                parentId: order.first_party_city
                            },
                            callback: function (data) {
                                data = JSON.parse(data);
                                var source = $("#area_list_tpl").html();
                                var template = Handlebars.compile(source);
                                var list = data
                                var html = template(list)
                                $('#area_list').html(html)
                                $("#area_list").val(order.first_party_area);
                            }
                        })*/
                        $("#area_list").attr('data-id',order.first_party_area);
                        $("#area_list").html(firstPartyMap.first_party_area_name);
                    }

                    //$(".autocomplete-input").val(order.first_party_address)
                    $("#address").html(order.first_party_address)
                    $("#aContractNo").text(order.contractNo + " 的贷款合同")
                    $("#contract_no").val(order.contractNo)
                    $("#bRealName").text(list2.content.realName)
                    $("#time").val(order.loanTime)
                    $("#applyMoney").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(order.applyMoney))
                    $("#CApplayMoney").text('(' + Constant.fn.chinese(order.applyMoney) + ')')
                    $("#money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(order.loan_amount))
                    $("#COutMoney").text('(' + Constant.fn.chinese(order.loan_amount) + ')')
                    //$("#bApplyMoney").append(' <div class="public-content-chinese ng-binding"></div>')
                    orderId = order.id;
                    //$.each()
                    //alert(typeof list.content.someAttType.attach_img);
                    //repaypalnState = list.content.order.id;
                } else {
                    Constant.fn.Message('F', list.msg)
                }

            }
        })


    }


    function UeditInit(i) {
        //初始化编辑器

        var initEditor = function () {
            editor = window.UE.getEditor('newDiv' + i);
            $('.D-messg-span span').unbind('click').on('click', function () {
                var placehold = $(this).data('placehold');
                editor.focus();
                editor.execCommand('inserthtml', placehold);//'{'+placehold+'}'
                return;
            });
            editors[i] = editor;
            editor.addListener("ready", function () {
                //editor.setContent('str');
                editor.setContent($(".doc_content_" + i).text());
            });
            //editor.setContent($(".doc_content_" + i).text());
        }

        if (window.UE && window.UE.version) {
            initEditor();
        } else {
            setTimeout(initEditor, 200);
        }
        //初始化编辑器 end
        /*setTimeout(function () {//加延迟用来显示内容
        }, 500);*/

    }

    // 还款计划end
    // 保存按钮判断
    function commit_fun(state) {
        // var content = [];
        if (isDoc == '-1') {
            //another_repayPlan_fun();
            if (repayment_way != '3') {
                var contractNo = $("#contract_no").val();
                if (!contractNo) {
                    Constant.fn.Message('I', "请先生成合同编号");
                    return;
                }
                //$('.contract_type_winBox').toggle();
                site.send({
                    url: 'manager/addContract.do',
                    data: {
                        oid: order_id,
                        contract_no: contractNo
                    }, callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == '1') {
                            repayPlan_fun();
                        } else {
                            Constant.fn.Message("F", data.msg);
                        }
                    }
                })
            }
            else {
                var contractNo = $("#contract_no").val();
                if (!contractNo) {
                    Constant.fn.Message('I', "请先生成合同编号");
                    return;
                }
                //$('.contract_type_winBox').toggle();
                site.send({
                    url: 'manager/addContract.do',
                    data: {
                        oid: order_id,
                        contract_no: contractNo
                    }, callback: function (data) {
                        data = JSON.parse(data);
                        if (data.type == '1') {
                            another_repayPlan_fun();
                        } else {
                            Constant.fn.Message("F", data.msg);
                        }
                    }
                })
            }
        }
        else {
            new_numData.contract_no = $("#contract_no").val();
            newData.contract_no = $("#contract_no").val();
            willBeSaved[0]['doc_content'] = editor.getContent();
            new_numData['content'] = willBeSaved;
            if (repayment_way != '3') {
                if (state == 'repayPlan') {
                    site.send({
                        url: 'manager/addContract.do',
                        async: false,
                        data: new_numData,
                        callback: function (data) {
                            var list = JSON.parse(data);
                            if (list.type == '1') {
                                //Constant.fn.Message('T', list.msg);
                                repayPlan_fun();
                            }
                            else {
                                Constant.fn.Message("F", list.msg);
                            }
                        }
                    })
                }
                else {
                    site.send({
                        url: 'manager/addContract.do',
                        async: false,
                        data: new_numData,
                        callback: function (data) {
                            var list = JSON.parse(data);
                            if (list.type == '1') {
                                Constant.fn.Message('T', list.msg);
                                //pjaxReload();
                            }
                            else {
                                Constant.fn.Message("F", list.msg);
                            }
                        }
                    })
                }
            } else {
                if (state == 'repayPlan') {
                    site.send({
                        url: 'manager/addContract.do',
                        async: false,
                        data: new_numData,
                        callback: function (data) {
                            var list = JSON.parse(data);
                            if (list.type == '1') {
                                //Constant.fn.Message('T', list.msg);
                                another_repayPlan_fun();
                            }
                            else {
                                Constant.fn.Message("F", list.msg);
                            }
                        }
                    })
                }
                else {
                    site.send({
                        url: 'manager/addContract.do',
                        async: false,
                        data: new_numData,
                        callback: function (data) {
                            var list = JSON.parse(data);
                            if (list.type == '1') {
                                Constant.fn.Message('T', list.msg);
                                pjaxReload();
                            }
                            else {
                                Constant.fn.Message("F", list.msg);
                            }
                        }
                    })
                }
            }
        }
    }

    $('#preserve').on('click', function () {
        /*if (state == 'repayPlan') {*/
        rapayPlan_data.type = $('input[name="contractType"]:checked').val()
        rapayPlan_data.loan_type = $('input[name="loan_type"]:checked').val()
        if (!rapayPlan_data.type && $('.contract_type_winBox #loanType').css('display') != 'none') {
            Constant.fn.Message('I', "请选择类型");
            return;
        }
        if (!rapayPlan_data.loan_type) {
            Constant.fn.Message('I', "请选择放款类型");
            return;
        }
        site.send({
            url: 'manager/preservationGenerateFundPlan.do',//
            async: false,
            data: rapayPlan_data,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    // $("#repayPlan_content").hide();
                    // $("#main_content").show();
                    selectFundPlan();
                    isGenerated = true;
                    Constant.fn.Message('T', list.msg);
                    $('.contract_type_winBox').toggle();
                    //pjaxReload();
                } else {
                    Constant.fn.Message('F', list.msg);
                }
            }
        })
        /*else {
//            var editor = window.UE.getEditor('newDiv' + state);
            var editor = editors[state];
            commitDocData.contract_no = $("#doc_number" + state).text();
            commitDocData.content = editor.getContent();
            site.send({
                url: 'manager/addContract.do',//
                async: false,
                data: commitDocData,
                callback: function (data) {
                    // console.log(data);

                    var list = JSON.parse(data);
                    if (list.type == 1) {

                    } else {
                        Constant.fn.Message('F', list.msg)
                    }
                }
            })
        }*/
        /*}*/
    })

// 预览方法
    function preview_fun(state, repayPlan) {
        previewData.id = $("#doc_id" + state).text();
        if (repayPlan == 'repayPlan') {
            window.open(Constant.param.domain + 'manager/doc/preview/pdf.do?oid=' + rapayPlan_data.oid);
        } else {
            previewData.oid = order_id;
            previewData.content = editor.getContent();
            site.send({
                url: "manager/PreviewInfo.do",
                //async: false,
                data: previewData,
                callback: function (data) {
                    var list = JSON.parse(data)
                    if (list.type == '1') {
                        //此处动态创建表单，跳转页面传值参数过长
                        //创建url
                        var url = "loanIng/contractManager/preview.html";
                        //创建要提交的参数
                        //设置属性
                        var form = $("<form></form>");

                        form.attr("action", url);
                        form.attr("method", "post");
                        form.attr("target", "_blank");

                        //创建input，即参数
                        var inputType = $("<input type='text' id='DivisionId' name='list'/>");
                        var inputTitle = $("<input type='text' id='d' name='title'/>");
                        var List = list.content;
                        inputType.attr("value", JSON.stringify(List.modelType));
                        inputTitle.attr("value", JSON.stringify(List.name));


                        //注入参数到表单
                        form.append(inputType);
                        form.append(inputTitle);
                        //form.append(inputNumber);
                        //form.append(inputStatus);
                        //form.append(inputPage);
                        form.appendTo("body");
                        form.hide();
                        //提交表单
                        form.submit();
                    } else {

                    }
                }
            })
            //window.open(Constant.param.domain + 'manager/doc/preview/pdf.do?id=' + previewData.id + '&oid=' + rapayPlan_data.oid);
        }

    }

// 搜索
    $(".serach_orderMortgageList").click(function () {
        var frontData = {
            roleId: Constant.getAurlparam("roleId"),
            audit_status: 0,
            susp_status: 1,
            pageNum: 1
        }
        if ($("#start_time").val() != '') {
            frontData.beginTime = $("#start_time").val();
        }
        if ($("#end_time").val() != '') {
            frontData.endTime = $("#end_time").val();
        }
        if ($("#seleNames").val() != '') {
            frontData.type = $("#seleNames").val();
        }
        if ($("#inputNames").val() != '' && $("#inputNames").val().trim()) {
            frontData.keyword = $("#inputNames").val();
        }
        if ($(".data_select").val() != '') {
            frontData.atId = $(".data_select").val();
        }
        if ($("#loan_way_select").val() != '') {
            frontData.loan_way = $("#loan_way_select").val();
        }
        if ($("#product_choose_list").val()) {
            frontData.product_id = $("#product_choose_list").val()
        }
        all_select(frontData);
    })


//scroll事件监听
    function scrollFun(i) {

        $(".bgSortScroll").scroll(function () {
            $(".messg-fixed2").css({'display': 'block'})
            $(".messg-fixed").css({'display': 'none'})

            var public_bgBotBtn = $(".public-bgBotBtn").height();
            var he = 150;
            var content_height = $("#repayDoc_content2").children(".public-content").eq(i).height() + 20 + 25 + 120 + 150;
            var scrolltop = $(this).scrollTop();
            var scroll = $(".bgSortScroll").height();
            var $bottomBtn = $(".public-bgBotBtn").height() + 10 + 10;
            var num = content_height - scroll - $bottomBtn;
            if (scrolltop > 200 && scrolltop < num) {

                $('.messg-fixed2').css({'display': 'block'})

            }
            else {

                $('.messg-fixed2').css({'display': 'none'})

            }


        })
    }

//实现智能联想
    var searData = {};  //用来存储地址信息

    var Intelligent_association = {

        creSele: function (obj) {
            var autocomplete = $(obj.el).autocomplete({
                hints: obj.data,
                width: obj.width,
                height: obj.height,
                val: obj.val,
                inputClass: obj.inputClass,
                placeholder: obj.placeholder,
                onSubmit: function (text) {
                    obj.backball(text)
                }
            })
            return autocomplete
        },

        initHuArea: function (idxData) {
            var _this = this;
            var huArea = _this.creSele({						//户口所在地
                el: '.huArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,									//默认input值
                inputClass: 'huInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.huArea = text
                }
            })
            $('.huInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    huArea.hints = _this.getCity()				//赋值数据进插件对象huArea
                }
            })
        },

        initHomeArea: function (idxData) {
            var _this = this
            var homeArea = _this.creSele({
                el: '.homeArea',							//页面上的span节点
                data: '',								//需要搜索的所有数据
                width: 158,
                height: 32,
                val: idxData,							//默认input值
                inputClass: 'homeInput',					//把动态生成的input class写进去 以免影响插件原有class
                placeholder: '请输入检索城市名称',
                backball: function (text) {				//用户选择后返回的值
                    searData.homeArea = text

                }
            })
            $('.homeInput').bind('keyup keydown', function (e) {		//监听用户敲击键盘时搜索数据
                if (e.which > 32 && e.which < 126) return
                if (/^[\u4e00-\u9fa5]*$/.test($(this).val())) {
                    homeArea.hints = _this.getCity()						//赋值数据进插件对象huArea
                }
            })
        },

        /*获取json文件中的城市*/
        getCity: function () {
            var city;
            $.ajax({
                type: 'get',
                url: 'static/cityjson.json',
                async: false,
                success: function (data) {
                    city = data
                }
            })
            return city
        },

        /*获取完json数据后转成id 传给后台*/
        getSearId: function (data) {
            var id, city = this.getCity()
            $.each(city, function (idx, item) {
                if (item.name == data) {
                    id = item.id.split(',')
                    return
                }
            })
            return id
        }
    }

//初始化智能搜索
    Intelligent_association.initHuArea();
    Intelligent_association.initHomeArea();

// 批量下载
    function allDownLoad() {

        $('.prog-c').css('width', '0px');
        $('.prog-rate i').text('0');
        $('.package_winBox').show();
        $('.downloaded').hide();
        $('.downloading').show();

        //进度条
        var time = 0;
        var prog = 0;
        var timer = setInterval(function () {
            time += 3;
            prog += 11;
            $('.prog-c').css('width', prog + 'px')
            $('.prog-rate i').text(time);
            if (time == 99) {
                clearInterval(timer);
            }
        }, 5)


        site.send({
            url: url.contractBatchDownload,//
            // async: false,
            data: allDownLoadData,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    //downloadFile(list.content.zipUrl)
                    $.each(list.content.zipMap, function (i, e) {
                        window.open(e.zipUrl);
                        /*var req = new XMLHttpRequest();
                        req.onprogress = function(evt){
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                console.log(percentComplete);
                            } else {
                                // Unable to compute progress information since the total size is unknown
                            }
                        };
                        req.open("GET", e.zipUrl);
                        req.send();*/
                        /*$.ajax({
                            url: e.zipUrl,
                            crossDomain: true,
                            xhrFields: {
                                withCredentials: true
                            },
                            headers: {'Access-Control-Allow-Origin': "*"},
                            //dataType: 'jsonp',
                            progress: function (evt) {
                                if (evt.lengthComputable) {
                                    var percentComplete = evt.loaded / evt.total;
                                    console.log(percentComplete);
                                } else {
                                    // Unable to compute progress information since the total size is unknown
                                }
                            },
                            success: function (data) {
                                console.log(data)
                            }
                        })*/
                    })

                    var source = $("#detail_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var html = template(list.content);
                    $("#detail_list").html(html);

                    Constant.fn.Message("T", list.msg);
                    //time = 100;
                    $('.prog-c').css('width', '376px');
                    $('.downloaded').show();
                    $('.downloading').hide();

                    //$('.package_winBox').();
                } else {
                    $('.package_winBox').hide();
                    Constant.fn.Message('F', list.msg)
                }
            }
        })
    }

//下载合同方法
    function downloadFile(src) {
        var $a = document.createElement('a');
        $a.setAttribute("href", src);
        $a.setAttribute("download", "");
        var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
        $a.dispatchEvent(evObj);
    }

    $("#commit_uploadaRegister").on('click', function () {
        var attachImg = new Array();

        //submitMortgageData.oid = order_id;
        submitMortgageData.mortgage = $("#mortgageInput").val();
        submitMortgageData.remarks = $("#mortgageTextarea").val();

        $.each($('[attachid=抵押] li'), function (i, e) {
            attachImg.push($(e).attr('href'));
        })

        submitMortgageData.attachImg = JSON.stringify(attachImg);
        //submitMortgageData.type = $('.UploadaRegister_Winbox input[name="faceResult"]:checked').val();
        submitMortgageData.userId = $(".UploadaRegister_Winbox .role_list option:selected").val();
        submitMortgageData.taskId = task_id;
        if (!submitMortgageData.mortgage) {
            Constant.fn.Message("I", "请输入抵押权")
            return;
        }

        if (!attachImg.length) {
            Constant.fn.Message("I", "请上传图片")
            return;
        }

        /*if (!submitMortgageData.type) {
            Constant.fn.Message('I', '请选择审核结果');
            return;
        }
        if (submitMortgageData.type == '1' && !submitMortgageData.userId) {
            Constant.fn.Message('I', '请选择提交对象');
            return;
        }*/
        if (!submitMortgageData.remarks) {
            Constant.fn.Message("I", "请输入备注")
            return;
        }

        site.send({
            url: 'manager/submitMortgage.do',//
            // async: false,
            data: submitMortgageData,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    //downloadFile(list.content.zipUrl)
                    $('.UploadaRegister_Winbox').toggle();
                    Constant.fn.Message('T', list.msg);
                    pjaxReload();
                } else {
                    Constant.fn.Message('F', list.msg)
                }
            }
        })
    })
    $('.cancelWindow').click(function () {
        $(".winBox").hide()
    })
// 修改收款确认
    $("#modifyCommit").click(function () {
        updataPersonalData.payee = $("#payee").val();
        updataPersonalData.account = $("#account").val();
        updataPersonalData.bank = $("#bank").val();
        site.send({
            url: 'manager/udpateAccountbank.do',//
            // async: false,
            data: updataPersonalData,
            callback: function (data) {
                var list = JSON.parse(data);
                if (list.type == 1) {
                    Constant.fn.Message('T', list.msg)
                    $(".modify_money_winBox").hide();
                } else {
                    Constant.fn.Message('F', list.msg)
                }
            }
        })
    })

// WebUploader实例
    var uploader;
    var attachId;

    function OSS_IMAGE_INIT(order_id, node_id) {

        var objdata = {
            upfile_nametype: 'random_name',//local_name random_name  上传文件的文件名类型
            url: localStorage.getItem('host') + "oss/getSignature.do"
        };
        // 当domReady的时候开始初始化
        $(".viewPic").unbind().on('click', function () {
            attachId = $(this).data('id');
            /*if (!order_id) {
                Constant.fn.Message('I', '请先录入订单');
                //$("#viewPic").unbind();
                return
            }*/
            /*if(!attach_id){
                $("#attachmentType").addClass('error');
                Constant.fn.Message('I','请选择类型');
                return
            }*/

            timeout : 30000,
                $.ajax({
                    type: "post",
                    url: objdata.url,
                    success: function (str) {
                        data = JSON.parse(str)
                        if (data.type > 0) {
                            try {
                                var re = data.content;
                                objdata.osssignature = {
                                    'key': re.dir,
                                    'policy': re.policy,
                                    'OSSAccessKeyId': re.accessId,
                                    'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                                    'signature': re.signature,
                                    'callback': re.callback,
                                    'expire': re.expire,
                                    'host': re.host
                                };
                            } catch (e) {
                                alert("系统错误");
                            }

                        } else {
                            alert("结果为空");
                        }
                        $("#image_upload_pop").toggle();

                        //设置居中
                        centerPosition($("#image_upload_pop .edui-dialog-body").get(0));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // alert("ajax error");
                    },
                    complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                        if (status == 'timeout') {
                            //alert('请求超时，请稍后再试！');
                        }
                    },
                    async: false
                });

            if (uploader) return;//界面已经存在，不去重新创建uploader了

            var $wrap = $('#uploader'),
                // 图片容器
                $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

                // 状态栏，包括进度和控制按钮
                $statusBar = $wrap.find('.statusBar'),

                // 文件总体选择信息。
                $info = $statusBar.find('.info'),

                // 上传按钮
                $upload = $wrap.find('.uploadBtn'),

                // 没选择文件之前的内容。
                $placeHolder = $wrap.find('.placeholder'),

                $progress = $statusBar.find('.progress').hide(),

                // 添加的文件数量
                fileCount = 0,

                // 添加的文件总大小
                fileSize = 0,

                acceptExtensions = [".png",".tif",".TIF", ".pdf", ".doc", ".docx", ".jpg", ".jpeg", ".gif", ".bmp", ".xls", ".xlsx"].join('').replace(/\./g, ',').replace(/^[,]/, ''),

                // 优化retina, 在retina下这个值是2
                ratio = window.devicePixelRatio || 1,

                // 缩略图大小
                thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,

                // 可能有pedding, ready, uploading, confirm, done.
                state = 'pedding',

                // 所有文件的进度信息，key为file id
                percentages = {},
                // 判断浏览器是否支持图片的base64
                isSupportBase64 = (function () {
                    var data = new Image();
                    var support = true;
                    data.onload = data.onerror = function () {
                        if (this.width != 1 || this.height != 1) {
                            support = false;
                        }
                    }
                    data.src = "";
                    return support;
                })(),

                // 检测是否已经安装flash，检测flash的版本
                flashVersion = (function () {
                    var version;

                    try {
                        version = navigator.plugins['Shockwave Flash'];
                        version = version.description;
                    } catch (ex) {
                        try {
                            version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
                        } catch (ex2) {
                            version = '0.0';
                        }
                    }
                    version = version.match(/\d+/g);
                    return parseFloat(version[0] + '.' + version[1], 10);
                })(),

                supportTransition = (function () {
                    var s = document.createElement('p').style,
                        r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
                    s = null;
                    return r;
                })(), _this = this;

            _this.imageList = [];
            if (!WebUploader.Uploader.support('flash') /* && WebUploader.browser.ie */) {

                // flash 安装了但是版本过低。
                if (flashVersion) {
                    (function (container) {
                        window['expressinstallcallback'] = function (state) {
                            switch (state) {
                                case 'Download.Cancelled':
                                    alert('您取消了更新！')
                                    break;

                                case 'Download.Failed':
                                    alert('安装失败')
                                    break;

                                default:
                                    alert('安装已成功，请刷新！');
                                    break;
                            }
                            delete window['expressinstallcallback'];
                        };

                        var swf = './expressInstall.swf';
                        // insert flash object
                        var html = '<object type="application/' + 'x-shockwave-flash" data="' + swf + '" ';

                        if (WebUploader.browser.ie) {
                            html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                        }

                        html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + swf + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>';

                        container.html(html);

                    })($wrap);

                    // 压根就没有安装。
                } else {
                    $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                }

                return;
            } else if (!WebUploader.Uploader.support()) {
                alert('Web Uploader 不支持您的浏览器！');
                return;
            }
            // 实例化
            uploader = WebUploader.create({
                pick: {
                    id: '#filePicker',
                    label: '点击选择图片'
                },
                resize: false,
                duplicate: true,
                accept: {
                    title: 'Images',
                    extensions: acceptExtensions,
                    // mimeTypes: 'filed/!*' //wuzhifeng 修改上传文件类型 图片的话 是
                    // image
                    mimeTypes: 'image/!*'
                },
                formData: {
                    uid: 123
                },
                dnd: '#edui114_body',
                paste: '#uploader',
                swf: '/tbpt/plugin/ueditor/third-party/webuploader/Uploader.swf',
                chunked: false,
                compress: false,
                chunkSize: 512 * 1024,
                server: objdata.osssignature.host,///tbpt/plugin/ueditor/jsp/controller.jsp?action=uploadimage
                //http://oss.aliyuncs.com/ http://tbptfile.oss-cn-beijing.aliyuncs.com/
                // runtimeOrder: 'flash',
                // server:
                // 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
                // server: 'http://www.2betop.net/fileupload.php',
                //

                // accept: {
                // title: 'Images',
                // extensions: 'gif,jpg,jpeg,bmp,png',
                // mimeTypes: 'image/!*'
                // },

                // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                disableGlobalDnd: false,
                auto: false,// {Boolean} [可选] [默认值：false] 设置为 true
                // 后，不需要手动调用上传，有文件选择即开始上传。
                fileNumLimit: 300,// 验证文件总数量, 超出则不允许加入队列。
                fileSizeLimit: 200 * 1024 * 1024, // 200 M
                fileSingleSizeLimit: 110 * 1024 * 1024 // 50 M
            });

            // 拖拽时不接受 js, txt 文件。
            uploader.on('dndAccept', function (items) {
                var denied = false, len = items.length, i = 0,
                    // 修改js类型
                    unAllowed = 'text/plain;application/javascript ';

                for (; i < len; i++) {
                    // 如果在列表里面
                    if (~unAllowed.indexOf(items[i].type)) {
                        denied = true;
                        break;
                    }
                }

                return !denied;
            });
            // 添加“添加文件”的按钮，
            uploader.addButton({
                id: '#filePicker2',
                label: '继续添加'
            });

            uploader.on('ready', function () {
                window.uploader = uploader;
            });

            //上传完成 服务器响应 不代表上传成功
            uploader.on('uploadSuccess', function (file, ret) {
                //console.log(fileCount);
                var $file = $('#' + file.id);
                if (ret._raw) {
                    _this.imageList.push({
                        succ: true
                    });
                    $file.append('<span class="success"></span>');
                    //图片
                    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/tiff') {
                        var index = $file.index();
                        /*if ($file.index() == 0) {
                            $('#picStay').prepend('原图:<a sort="' + $file.index() + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            $('#picStay').prepend('<img sort="' + $file.index() + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {*/
                        var aSortArr = [];
                        if (!$('#picStay a').length) {
                            $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                        } else {
                            $.each($('#picStay a'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    aSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (aSortArr.length) {
                                $("#picStay a").eq(aSortArr.length - 1).after('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                            else {
                                $('#picStay').prepend('原图:<a sort="' + index + '" playHref="' + objdata.osssignature.host + "/" + file.path + '/tupian_compress" href="' + objdata.osssignature.host + "/" + file.path + '" target="_blank" >' + objdata.osssignature.host + "/" + file.path + '</a>');
                            }
                        }


                        var imgSortArr = [];
                        if (!$('#picStay img').length) {
                            $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                        } else {
                            $.each($('#picStay img'), function (i, e) {
                                if ($(e).attr('sort') < index) {
                                    imgSortArr.push($(e).attr('sort'))
                                }
                            })

                            if (imgSortArr.length) {
                                $("#picStay img").eq(imgSortArr.length - 1).after('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                            } else {
                                $('#picStay').prepend('<img sort="' + index + '" src="' + objdata.osssignature.host + "/" + file.path + '?x-oss-process=image/resize,m_lfit,h_56,w_36" />');
                            }
                        }
                    }
                } else {
                    showError(file.statusText);
                    $file.find('.error').text("失败").show();
                    console.log("上传失败");
                    $('body').append("上传失败");
                }

            });

            uploader.on('uploadBeforeSend', function (obj, data, headers) {
                //TODO   如果同一个页面上传多次  需要处理签名逻辑   不用每次都签名
                //debugger
                //赋值参数
                data = $.extend(data, objdata.osssignature);
                headers['Access-Control-Allow-Origin'] = "*";

                //设置文件路径
                data.key = data.key + "/" + calculate_object_name(data.name, objdata.upfile_nametype);
                obj.filepath = data.key;
                obj.file.path = data.key;
            });

            //得到文件名 type local_name random_name
            function calculate_object_name(filename, type) {
                if (type && type == 'local_name') {
                    return "${filename}";
                } else {//随机生成文件名
                    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                    var maxPos = chars.length;
                    var random_string = '';
                    for (i = 0; i < 10; i++) {
                        random_string += chars.charAt(Math.floor(Math.random() * maxPos));
                    }
                    var pos = filename.lastIndexOf('.')
                    var suffix = ''
                    if (pos != -1) {
                        suffix = filename.substring(pos);
                    }
                    return random_string + new Date().getTime() + suffix;
                }
            }

            // 当有文件添加进来时执行，负责view的创建
            function addFile(file) {
                var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'),

                    $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li),
                    $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'),
                    $info = $('<p class="error"></p>'),

                    showError = function (code) {
                        switch (code) {
                            case 'exceed_size':
                                text = '文件大小超出';
                                break;

                            case 'interrupt':
                                text = '上传暂停';
                                break;

                            default:
                                text = '上传失败，请重试';
                                break;
                        }

                        $info.text(text).appendTo($li);
                    };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    // @todo lazyload
                    $wrap.text('预览中');
                    uploader.makeThumb(file, function (error, src) {
                        var img;

                        if (error) {
                            $wrap.text('不能预览');
                            return;
                        }

                        if (isSupportBase64) {
                            img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }
                    }, thumbnailWidth, thumbnailHeight);

                    percentages[file.id] = [file.size, 0];
                    file.rotation = 0;
                }


                file.on('statuschange', function (cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        console.log(file.statusText);
                        showError(file.statusText);
                        percentages[file.id][1] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[file.id][1] = 0;
                    } else if (cur === 'progress') {
                        $info.remove();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                        //$li.append('<span class="success"></span>');
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });
                uploader.on('uploadAccept', function (file, response) {
                    var hasError = (response['error'] !== undefined);
                    if (hasError) {
                        // 通过return false来告诉组件，此文件上传有错。
                        return false;
                    }
                    ;
                });
                uploader.on("uploadFinished", function () {
                    // uploader.reset();
                    // uploader;
                });

                $li.on('mouseenter', function () {
                    $btns.stop().animate({
                        height: 30
                    });
                });

                $li.on('mouseleave', function () {
                    $btns.stop().animate({
                        height: 0
                    });
                });

                $btns.on('click', 'span', function () {
                    var index = $(this).index(), deg;

                    switch (index) {
                        case 0:
                            uploader.removeFile(file);
                            return;

                        case 1:
                            file.rotation += 90;
                            break;

                        case 2:
                            file.rotation -= 90;
                            break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform': deg,
                            '-mos-transform': deg,
                            '-o-transform': deg,
                            'transform': deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.appendTo($queue);
            }

            // 负责view的销毁
            function removeFile(file) {
                var $li = $('#' + file.id);

                delete percentages[file.id];
                updateTotalProgress();
                $li.off().find('.file-panel').off().end().remove();
            }

            function updateTotalProgress() {
                var loaded = 0, total = 0, spans = $progress.children(), percent;

                $.each(percentages, function (k, v) {
                    total += v[0];
                    loaded += v[0] * v[1];
                });

                percent = total ? loaded / total : 0;

                spans.eq(0).text(Math.round(percent * 100) + '%');
                spans.eq(1).css('width', Math.round(percent * 100) + '%');
                updateStatus();
            }

            function updateStatus() {
                var text = '', stats;

                if (state === 'ready') {
                    text = '选中' + fileCount + '张图片，共' + WebUploader.formatSize(fileSize) + '。';
                } else if (state === 'confirm') {
                    stats = uploader.getStats();
                    if (stats.uploadFailNum) {
                        text = '已成功上传' + stats.successNum + '张照片，' + stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                    }

                } else {
                    stats = uploader.getStats();
                    text = '共' + fileCount + '张（' + WebUploader.formatSize(fileSize) + '），已上传' + stats.successNum + '张';

                    if (stats.uploadFailNum) {
                        text += '，失败' + stats.uploadFailNum + '张';
                    }
                }

                $info.html(text);
            }

            function setState(val) {
                var file, stats;

                if (val === state) {
                    return;
                }

                $upload.removeClass('state-' + state);
                $upload.addClass('state-' + val);
                state = val;

                switch (state) {
                    case 'pedding':
                        $placeHolder.removeClass('element-invisible');
                        $queue.hide();
                        $statusBar.addClass('element-invisible');
                        uploader.refresh();
                        break;

                    case 'ready':
                        $placeHolder.addClass('element-invisible');
                        $('#filePicker2').removeClass('element-invisible');
                        $queue.show();
                        $statusBar.removeClass('element-invisible');
                        uploader.refresh();
                        $upload.text('开始上传').removeClass('disabled');
                        break;

                    case 'uploading':
                        $('#filePicker2').addClass('element-invisible');
                        $progress.show();
                        $upload.text('暂停上传');
                        break;

                    case 'paused':
                        $progress.show();
                        $upload.text('继续上传');
                        break;

                    case 'confirm':
                        $progress.hide();
                        $upload.text('开始上传').addClass('disabled');

                        stats = uploader.getStats();
                        if (stats.successNum && !stats.uploadFailNum) {
                            setState('finish');
                            return;
                        }
                        break;
                    case 'finish':
                        stats = uploader.getStats();
                        if (stats.successNum) {

                            // WuZhiFeng

                        } else {
                            // 没有成功的图片，重设
                            state = 'done';
                            location.reload();
                        }
                        $('#filePicker2').removeClass('element-invisible');
                        $upload.text('开始上传').removeClass('disabled');
                        break;
                }

                updateStatus();
            }

            uploader.onUploadProgress = function (file, percentage) {
                var $li = $('#' + file.id), $percent = $li.find('.progress span');

                $percent.css('width', percentage * 100 + '%');
                if ($.isEmptyObject(percentages)) {
                    return false;
                }
                percentages[file.id][1] = percentage;
                updateTotalProgress();
            };

            uploader.onFileQueued = function (file) {
                fileCount++;
                fileSize += file.size;

                if (fileCount === 1) {
                    $placeHolder.addClass('element-invisible');
                    $statusBar.show();
                }

                addFile(file);
                setState('ready');
                updateTotalProgress();
            };

            uploader.onFileDequeued = function (file) {
                fileCount--;
                fileSize -= file.size;

                if (!fileCount) {
                    setState('pedding');
                }

                removeFile(file);
                updateTotalProgress();

            };

            uploader.on('all', function (type) {
                var stats;
                switch (type) {
                    case 'uploadFinished':
                        setState('confirm');
                        break;

                    case 'startUpload':
                        setState('uploading');
                        break;

                    case 'stopUpload':
                        setState('paused');
                        break;

                }

            });

            uploader.onError = function (code) {
                if (code == 'Q_TYPE_DENIED') {
                    Constant.fn.Message("I", "不支持该文件类型，请选择图片类型文件");
                }
                if (code == 'Q_EXCEED_NUM_LIMIT') {
                    Constant.fn.Message("I", "只能上传单张图片");
                }
                // alert( 'Eroor: ' + code );
            };

            $upload.on('click', function () {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                if (state === 'ready') {
                    uploader.upload();
                } else if (state === 'paused') {
                    uploader.upload();
                } else if (state === 'uploading') {
                    uploader.stop();
                }
            });

            $info.on('click', '.retry', function () {
                uploader.retry();
            });

            $info.on('click', '.ignore', function () {
                alert('todo');
            });

            $upload.addClass('state-' + state);
            updateTotalProgress();


        });

    }

    var resetUploader = function () {
        if (uploader) {
            //重新设置页面
            for (var i = 0; i < uploader.getFiles().length; i++) {
                uploader.removeFile(uploader.getFiles()[i]);
            }
            uploader.reset();
        }
        $('.webuploader-element-invisible').val('');
    };

    $(".closed").unbind();
    $(".sure").unbind();

    $(".closed").on('click', function () {
        resetUploader();
        $('#image_upload_pop').toggle();
        $("#picStay").html("");
    })

    $(".sure").on('click', function () {

        var attachImg = [];
        var attachimg = [];
        var flag2 = false;
        /*var status = uploader.getStats();
        if (status.queueNum) {
            $(".statusBar .info").html("还有" + status.queueNum + "张图片未上传");
            return
        }*/
        $('#image_upload_pop').toggle();
        resetUploader();

        var img = $("#picStay a");

        if (img.length) {
            $.each(img, function (i, e) {
                attachImg.push(
                    {
                        playHref: $(e).attr('playhref'),
                        href: $(e).attr('href'),
                        attachId: attachId
                    }
                );
            })

            $.each(img, function (i, e) {
                attachimg.push($(e).attr('href'))
            })

            var sameAttach = $('[attachid=' + attachId + '] li');
            if (sameAttach.length) {
                $.each(sameAttach, function (i, e) {
                    attachimg.push($(e).attr('href'))
                })
            }
        }

        if (attachImg.length) {
            if ($('[attachId]').length) {
                $.each($('[attachId]'), function (i, e) {
                    if (attachImg[0].attachId == $(e).attr('attachId')) {
                        $.each(attachImg, function (ii, ee) {
                            if (Constant.fn.getFileType(ee.href) == 'pdf') {
                                $(e).append('<a href=' + Constant.fn.getFileName(ee.href) + ' target="_blank">' + ee.href + '</a>')
                            }
                            else {
                                $(e).append('<li href=\"' + ee.href + '\">   \n' +
                                    '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                    '<i class="delSingleAttach iconfont icon-minus">\n' +
                                    '</i>\n' +
                                    '</li>')
                            }
                        })

                        $("#picStay").html("");
                        flag2 = false;
                    }
                })

                if (flag2) {
                    $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                    $.each(attachImg, function (ii, ee) {
                        var gallery = $('[attachId=' + ee.attachId + ']');
                        if (Constant.fn.getFileType(ee.href) == 'pdf') {
                            gallery.append('<a href=' + Constant.fn.getFileName(ee.href) + ' target="_blank">' + ee.href + '</a>')
                        } else {
                            gallery.append('<li href=\"' + ee.href + '\">   \n' +
                                '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                                '<i class="delSingleAttach iconfont icon-minus">\n' +
                                '</i>\n' +
                                '</li>')
                        }
                    })

                    //imgList(data.content[0].attachId);
                    $("#picStay").html("");

                }
            }

            else {
                $('#image_list').append("<tr><td>" + data.content[0].attachName + "</td><td class=\"minImg\"><div id=\"gallery" + data.content[0].attachId + "\" attachName=\"" + data.content[0].attachName + "\" attachId=\"" + data.content[0].attachId + "\" allid=" + data.content[0].id + "></div></td><td><i class=\"delAttach iconfont icon-shanchu\"></i></td></tr>");
                $.each(attachImg, function (ii, ee) {
                    var gallery = $('[attachId=' + ee.attachId + ']');
                    if (Constant.fn.getFileType(ee.href) == 'pdf') {
                        gallery.append('<a href=' + Constant.fn.getFileName(ee.href) + ' target="_blank">' + ee.href + '</a>')
                    } else {
                        gallery.append('<li href=\"' + ee.href + '\">   \n' +
                            '<img class="img_00" url="' + ee.href + '" src="' + ee.playHref + '">\n' +
                            '<i class="delSingleAttach iconfont icon-minus">\n' +
                            '</i>\n' +
                            '</li>')
                    }
                })

                //imgList(data.content[0].attachId);
                $("#picStay").html("");
            }
            Constant.fn.initScroll();
            $('[id^="gallery"]').parents('.winBox1').viewer('destroy').viewer();
        }
        //删除单张图片
        $('.delSingleAttach').unbind().on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).parents('li').remove();
            Constant.fn.initScroll();
        })

    })

    OSS_IMAGE_INIT()


    /*//省市区联动
    site.send({
        url: url.ajaxqueryRegion,
        data: {
            parentId: 0
        },
        callback: function (data) {
            data = JSON.parse(data);
            var source = $("#province_list_tpl").html();
            var template = Handlebars.compile(source);
            var list = data
            var html = template(list)
            $('#province_list').append(html)
            //$('#rprovince_list').append(html)
        }
    })*/

    $("#province_list").on("change", function () {
        if (!$(this).val()) {
            $("#city_list").html('<option value="" selected="selected">选择市</option>');
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        }
        else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#city_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#city_list').html(html)
                }
            })
        }
    })

    $("#city_list").on("change", function () {
        if (!$(this).val()) {
            $("#area_list").html('<option value="" selected="selected">选择区县</option>');
        } else {
            site.send({
                url: url.ajaxqueryRegion,
                data: {
                    parentId: $(this).val()
                },
                callback: function (data) {
                    data = JSON.parse(data);
                    var source = $("#area_list_tpl").html();
                    var template = Handlebars.compile(source);
                    var list = data
                    var html = template(list)
                    $('#area_list').html(html)
                }
            })
        }
    })

    $(".canCover").on('click', function () {
        $(this).parents('.winBox').hide();
    })

})


/**
 * 从ueditor.all.js里面拷贝的拖拽方法
 */
var _onTitlebarMouseDown = function (event, el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var domUtils = baidu.editor.dom.domUtils;
    var rect;
    var me = this;
    var dialogId = el.getAttribute('id');//'image_upload_pop';

    var safeSetOffset = function (offset) {
        // var me = this;
        var el = getDom();
        var vpRect = uiUtils.getViewportRect();
        var rect = uiUtils.getClientRect(el);
        var left = offset.left;
        if (left + rect.width > vpRect.right) {
            left = vpRect.right - rect.width;
        }
        var top = offset.top;
        if (top + rect.height > vpRect.bottom) {
            top = vpRect.bottom - rect.height;
        }
        el.style.left = Math.max(left, 0) + 'px';
        el.style.top = Math.max(top, 0) + 'px';
    }
    var getDom = function (name) {
        if (!name) {
            return document.getElementById(dialogId);
        } else {
            return document.getElementById(dialogId + '_' + name);
        }
    };

    uiUtils.startDrag(event, {
        ondragstart: function () {
            rect = uiUtils.getClientRect(getDom());
            // me.getDom('contmask').style.visibility = 'visible';
            // me.dragMask.show(me.getDom().style.zIndex - 1);
        },
        ondragmove: function (x, y) {
            var left = rect.left + x;
            var top = rect.top + y;
            safeSetOffset({
                left: left,
                top: top
            });
        },
        ondragstop: function () {
            // me.getDom('contmask').style.visibility = 'hidden';
            // domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
            // me.dragMask.hide();
        }
    });

};

var centerPosition = function (el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var vpRect = uiUtils.getViewportRect();
    var rect = uiUtils.getClientRect(el);
    var left = vpRect.width / 2 - rect.width / 2;
    var top = vpRect.height / 2 - rect.height / 2;

    el.style.left = Math.max(left, 0) + 'px';
    el.style.top = Math.max(top, 0) + 'px';
};